package controller;

import helper.Calendr;
import helper.Formatter;
import helper.UserSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import databeans.Fund;
import databeans.FundHistory;
import databeans.Payment;
import databeans.Transaction;

import model.CustomerDAO;
import model.Model;
import model.PaymentDAO;
import model.TransactionDAO;

public class EmployeeDepositCheckAction extends Action {

	private PaymentDAO paymentDAO;
	private CustomerDAO customerDAO;
	public EmployeeDepositCheckAction(Model model) {
		paymentDAO = model.getPaymentDAO();
        customerDAO =  model.getCustomerDAO();
	}

	@Override
	public String getName() {
		return "employeeDepositCheck.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		// set pages
		String loginPage = "employee/employee-login.jsp";
		String originPage = "employee/deposit-check.jsp";
		String successPage = originPage;
		// set
		Employee employee = null;
		Customer customer = null;
		
		//Errors
		List<String> errors = new ArrayList<String>();
	    List<String> messages = new ArrayList<String>();
	    
	    //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        request.setAttribute("page", "check-deposit");
        
        

        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        if (employee == null) {
            errors.add("You need to log in");
            return loginPage ;
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }

        
        try {
			Customer[] customers = customerDAO.getCustomers();
			request.setAttribute("customers", customers);
		} catch (DAOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
	    //Get Params
	    
		String requestType = request.getParameter("Submit");    
        String customerID = request.getParameter("txtCustomerID");
        String amount = request.getParameter("txtAmount");
        long cash = 0;

        //Set Attributes 
        request.setAttribute("txtCustomerID", customerID);
        request.setAttribute("txtAmount", amount);
        
        
        if (requestType == null) {
            //messages.add("To buy the fund. Please fill the form below");
        	request.setAttribute("txtCustomerID", "0");
            return originPage;
        }
        
        //validate the input
 
        if (customerID.trim().equals("")) {
        	request.setAttribute("txtCustomerID", "0");
            errors.add("Please choose a Customer Account to deposit Check into");
            return originPage;
        }
        
        if (amount.trim().equals("")) {
            errors.add("Please enter a value for the Check Amount");
            return originPage;
        }

        //check if double value inputted is A double
        if (!Formatter.isDouble(amount)){
            //messages.add("You must input a number in amount field");
            errors.add("Invalid input in price field. Please check.");
            return originPage;
        }
        
        
        if (Double.parseDouble(amount) <= 0) {
            errors.add("Please enter a valid Check Amount");
            return originPage;
        }
        


          //check if double has 2 decimal place
          if(Formatter.numberOfDecimal(amount)>2) {
              messages.add("CFA only tracks amount up to two decimal place. Please reenter the amount");
              errors.add("Accuracy could not be captured");
              return originPage;
          }
          

          
          //ensure no negative number
          if ( Double.parseDouble(amount) <= 0.00 ){
              //messages.add("The amount should not be negative");
              errors.add("Invalid input for Number of Shares to purchase. Please check.");
              return originPage;
          }

          //ensure not too much check
          if ( Double.parseDouble(amount) > 1000000000000.00 ){
              errors.add("The number you put is too large.");
              return originPage;
          }
        
        // Find the 
        try{
        	System.out.println("customer ID = " + customerID);
            customer = customerDAO.lookup(Integer.parseInt(customerID));
            cash = customer.getCash();
            
        } catch (NumberFormatException e1) {
            errors.add("Customer associated could not be retrieved");
            return originPage;
        } catch (DAOException efundtry) {
            errors.add("Customer associated could not be retrieved");
            return originPage;
        }
        
        /*
        try {
			customerDAO.addCash(Integer.parseInt(customerID), Formatter.prepCashFromView(amount));
		} catch (NumberFormatException e1) {
			errors.add("Wrong with the amount number or customer Id");
			return originPage;
		} catch (DAOException e1) {
			errors.add("Wrong with the amount number or customer Id");
			return originPage;
			
		}
		*/
        System.out.println("Formatter result " + Formatter.prepCashFromView(amount) );
        try {
            
            Payment tempTrans = new Payment();
            tempTrans.setCustomerID(Integer.parseInt(customerID));
            tempTrans.setSubmitDate(Calendr.getTodaysDate());
            tempTrans.setTransactionType(Transaction.CHECK_DEPOSIT);
            tempTrans.setAmount(Formatter.prepCashFromView(amount));
            tempTrans.setExecuted(false);

            //push those transaction object into database
            paymentDAO.create(tempTrans);
            
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            session.setAttribute("employee", employee );
            request.setAttribute("txtCustomerID", "0");;
            request.setAttribute("txtAmount", "");
            
            //set the welcome message
            messages.add("Succesfully deposited check for customer <b>" + customer.getFirstName() + " " + customer.getLastName() + "</b> with amount <b>$" + Formatter.prepCashToView(tempTrans.getAmount()) + "</b>");
            return successPage;

        } catch (Exception e) {
            errors.add("Unable to deposit Check. Please try again later.");
            System.out.println(e.getMessage());
            return originPage;
        }
	}

}
